// pages/homePageInfo/experienceDotsList/experienceDotsList.js
import throttle from '../../../utils/throttle.js';
import { hasPermission } from '../../../utils/tools';
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        idItem: '', //经验id
        pageNum: 0,
        loading: true,
        loadingAll: false,
        title: '', //经验类型
        extypeid: '',
        experienceArr: [],
        activeExpIndex: null, // 当前经验索引
        //操作弹框
        show: false,
        actions: [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ],
        activeCreateUid: '',
        showNext: false,
        permissionList: ['00', '01'],
    },
    // 添加经验
    addExperience() {
        wx.navigateTo({
            url: `../../../releasePage/pages/addExperience/addExperience?type=01&typename=${this.data.title}&extypeid=${this.data.extypeid}&current=1`,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 设置页面顶部title
        wx.setNavigationBarTitle({
            title: options.title,
        });

        let that = this;
        that.setData({
            title: options.title,
            extypeid: options.extypeid,
        });
        that.getExperienceList();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    refresh() {
        let that = this;
        that.setData({
            noInfo: false,
            pageNum: 0,
            loading: true,
            loadingAll: false,
            experienceArr: [],
        });
        that.getExperienceList();
    },

    // 编辑功能
    edit(e) {
        let { uid, id, excellentflg, index, authority } = e.detail;

        let actions = [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ];

        if (hasPermission(this.data.permissionList) || authority) {
            if (excellentflg === '00') {
                actions.splice(0, 0, {
                    name: '设置为精华',
                    color: '#333333',
                    id: 3,
                });
            } else {
                actions.splice(0, 0, {
                    name: '取消精华',
                    color: '#333333',
                    id: 4,
                });
            }

            actions.splice(2, 0, {
                name: '转移至',
                color: '#333333',
                id: 5,
            });
        }

        this.setData({
            show: true,
            activeCreateUid: uid,
            idItem: id,
            actions,
            activeExpIndex: index,
        });
    },
    //取消
    onCancel(e) {
        this.setData({
            show: false,
        });
    },
    onSelect(e) {
        let _that = this;
        if (e.detail.id == 2) {
            wx.navigateTo({
                url: `../../../releasePage/pages/addExperience/addExperience?type=01&id=${_that.data.idItem}&current=1`,
            });
        } else if (e.detail.id == 1) {
            wx.showModal({
                title: '提示',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        _that.deleteExperience();
                    } else {
                        console.log('点击取消回调');
                    }
                },
            });
        } else if (e.detail.id == 3) {
            _that.setExperienceExcellent('01');
        } else if (e.detail.id == 4) {
            _that.setExperienceExcellent('00');
        } else if (e.detail.id == 5) {
            _that.setData({
                showNext: true,
            });
        }
        _that.setData({
            show: false,
        });
    },
    // 预览图片
    previewImage(e) {
        let index = e.currentTarget.dataset.index;
        let images = e.currentTarget.dataset.images;
        wx.previewImage({
            current: images[index],
            urls: images,
        });
    },
    //获取经验列表
    getExperienceList() {
        let _that = this;
        if (!_that.data.loadingAll) {
            _that.setData({
                pageNum: _that.data.pageNum + 1,
                loading: true,
                loadingAll: false,
            });
            wx.request({
                url: app.globalData.rootPath + `cjMap/getExperienceList`,
                method: 'GET',
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                },
                data: {
                    authId: app.globalData.authId,
                    pageNo: _that.data.pageNum,
                    pageSize: 10,
                    extypeid: _that.data.extypeid || '',
                },
                success: function (res) {
                    if (res.data.status == 0) {
                        if (res.data.data.length) {
                            for (let i = 0; i < res.data.data.length; i++) {
                                res.data.data[i].createtime = app.timeago(
                                    res.data.data[i].createtime
                                );
                                res.data.data[i].ellipsis =
                                    res.data.data[i].content.length > 168;
                                _that.data.experienceArr.push(res.data.data[i]);
                            }
                        }
                        _that.setData({
                            experienceArr: _that.data.experienceArr,
                            loading: false,
                        });
                        if (
                            res.data.pager.currentPage >=
                            res.data.pager.totalPages
                        ) {
                            _that.setData({
                                loadingAll: true,
                            });
                        }
                    } else {
                        _that.setData({
                            loadingAll: true,
                            loading: false,
                        });
                    }
                },
            });
        }
    },

    // 删除经验
    deleteExperience() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `cjMap/deleteExperience`,
            method: 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
                authId: app.globalData.authId,
                id: _that.data.idItem,
            },
            success: function (res) {
                if (res.data.status === '0') {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    _that.hiddenListItem(
                        'experienceArr',
                        _that.data.activeExpIndex
                    );
                    let pages = getCurrentPages(); //当前页面栈
                    let prevPage = pages[pages.length - 2]; //上一页面
                    let prevPage2 = pages[pages.length - 3]; //上一页面
                    prevPage.refresh();
                    if (prevPage2 && typeof prevPage2.refresh == 'function') {
                        try {
                            prevPage2.refresh();
                        } catch (err) {
                            return;
                        }
                    }
                }
            },
        });
    },

    // 设为精华和取消精华
    setExperienceExcellent(excellentflg) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/setExperienceExcellent?authId=${app.globalData.authId}`,
            header: {
                'content-type': 'application/json',
            },
            data: {
                excellentflg,
                id: _that.data.idItem,
            },
            success: function (res) {
                if (res.data.status == '0') {
                    _that.setData({
                        [`experienceArr[${_that.data.activeExpIndex}].excellentflg`]: excellentflg,
                    });

                    _that.onCancel();

                    app.globalData.expRefresh = true;

                    let pages = getCurrentPages(); //当前页面栈

                    let prevPage = pages[pages.length - 2];
                    if (prevPage && typeof prevPage.refresh == 'function') {
                        prevPage.refresh();
                    }

                    let prevPage2 = pages[pages.length - 3];
                    if (prevPage2 && typeof prevPage2.refresh == 'function') {
                        prevPage2.refresh();
                    }

                    let prevPage3 = pages[pages.length - 4];
                    if (prevPage3 && typeof prevPage3.refresh == 'function') {
                        prevPage3.refresh();
                    }
                }
            },
        });
    },

    changeNav: throttle(
        (e) => {
            let { nav } = e.currentTarget.dataset;
            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 删除经验时，前端先隐藏这条经验而不是直接刷新
    hiddenListItem(arrName, index) {
        this.data[arrName].splice(index, 1);
        this.setData({
            [arrName]: this.data[arrName],
        });
    },

    // 处理点赞同步问题
    handleLike(e) {
        let { id, praiseflg, praisecnt } = e.detail;
        let expIndex = -1;
        this.data.experienceArr.map((item, index) => {
            if (item.id === id) {
                expIndex = index;
            }
        });
        if (expIndex > -1) {
            this.setData({
                [`experienceArr[${expIndex}].praiseflg`]: praiseflg,
                [`experienceArr[${expIndex}].praisecnt`]: praisecnt,
            });
        }
    },

    // 点击评论图标直接跳转到底部评论区
    handleComment: throttle(
        (e) => {
            const { id } = e.detail;
            wx.navigateTo({
                url: `../../../functionPage/pages/experienceDetail/experienceDetail?id=${id}&comment=1`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 刷新某一条经验的评论数
    refreshCommentNum(params) {
        const { id, commentcount } = params;
        const expIndex = this.data.experienceArr.findIndex((item) => {
            return item.id === id;
        });
        if (expIndex > -1) {
            this.setData({
                [`experienceArr[${expIndex}].commentcount`]: commentcount,
            });
        }
    },

    // 转移上一步
    upBtn(e) {
        this.setData({
            showNext: false,
            show: true,
        });
        this.tabbarShow();
    },

    hideTranferCover(e) {
        this.setData({
            showNext: false,
        });
    },
});
